<?php
class Friendship_Model_Dbtable_RequestFriendship extends Zend_Db_Table_Abstract{
	protected $_name = 'request_friendships';
	
	public function addrequestfriends($user1, $user2){
		$dt = getdate();
		$date = $dt['year'].'/'.$dt['mon'].'/'.$dt['mday'];
		$data = array(
				'request_friendship_user1' => $user1,
				'request_friendship_user2' => $user2,
				'request_friendship_date' => $date,
				'request_friendship_read' => '0',
		);
		$this->insert($data);
	}

	public function acceptrequestfriends($user1, $user2){
		$this->delete('request_friendship_user1 =' . (int)$user1 .' and request_friendship_user2 = ' .(int)$user2);
		
		$arf = new Friendship_Model_Dbtable_Friendship();
		$arf -> addfriends($user1, $user2);
	}

	public function unacceptrequestfriends($user1, $user2){
		$this->delete('request_friendship_user1 =' . (int)$user1 .' and request_friendship_user2 = ' .(int)$user2);
	}
	
	//Ko sai nua
	public function changeRelationship($id1, $id2){
		$query = $this->select();
		$query->from('request_friendships',array('request_friendship_read'));
		$query->where('request_friendship_user1 =?',$id1);
		$query->where('request_friendship_user2 =?',$id2);
		$data = $this->fetchAll($query)->toArray();
		//$data->toArray();
		$fs = $data['0']['request_friendship_read'];
		if($fs=='1')
    		$this->update(array('request_friendship_status'=>'0'), 'request_friendship_user1 = '.$id1.' and request_friendship_user2 = '. $id2);
		else 
			$this->update(array('request_friendship_status'=>'1'), 'request_friendship_user1 = '.$id1.' and request_friendship_user2 = '. $id2);
	}
	

	public function checkLimitCreateRelationship($id,$date){
		$query = $this->select();
		$query->from('request_friendships');
		$query->where('request_friendship_user1 =?',$id);
		$query->where('request_friendship_date =?',$date);
		$data = $this->fetchAll($query)->toArray();
		$count = count($data);
		if($count == '3')
			return 1;
		else
			return 0;
	}
	
	public function getrequestfriendships($iduser){
		$query = $this->select();
		$query->from('request_friendships',array('request_friendship_user1','request_friendship_read'));
		$query->where('request_friendship_user2 =?',$iduser);
		$data = $this->fetchAll($query)->toArray();
		$tong = count($data);
		$num_request=0;
		$j=0;
		$friendrequest = array();
		for($i=0;$i<$tong;$i++)
		{
			if($data[$i]['request_friendship_read']==0)
			{
				$num_request++;
				$friendrequest[$j++]['friendrequest']=$data[$i]['request_friendship_user1'];
			}
		}
		return $friendrequest;
	}
	
}











